//
//  ProfileViewController.swift
//  AreaChainblock
//
//  Created by 赵佟越 on 2018/9/18.
//  Copyright © 2018年 zhaotongyue. All rights reserved.
//

import UIKit
import Eureka
import Alamofire
import SwiftyUserDefaults

class ProfileViewController: FormViewController {

    override func viewWillAppear(_ animated: Bool) {
//       getData()
    }
    var myuserModel = userModel()
    override func viewDidLoad() {
        super.viewDidLoad()
//        self.myuserModel = userModel()
        layoutNav()
        let backImageView = UIImageView.init()
        backImageView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
        backImageView.image = UIImage.init(named: "底色 拷贝 2@2x")
        self.view.addSubview(backImageView)
        self.view.sendSubview(toBack: backImageView)
        
        self.makeBaseUI()
        getData()
        
        super.tableView.backgroundColor = UIColor.clear
//        super.tableView.backgroundColor = UIColor("#EEF0F7")
        super.tableView.separatorStyle = .none
        
        
        
        // Do any additional setup after loading the view.
    }
    func getData() {
        MyNetwork.request(target: .userinfo(user_id: Defaults[.userID]!), success: { (result) in
            kLog(result)
            let needModel = BaseModel()
            needModel.yy_modelSet(with: result as! [AnyHashable : Any])
            
            if needModel.code == 1111{
                self.myuserModel.yy_modelSet(withJSON:(result as AnyObject)["data"]);
//
                
                
                let url1 = URL( string:String(format: "http://renedescartes.io%@", self.myuserModel.avatar!))
                //44f5dd23306614e83a40354a719e143e.jpg
                let data1 = try? Data( contentsOf:url1!)
                let tempStr :String!
                if self.myuserModel.check_type == "1"{
                    tempStr = XALanguageManager.getString(key: "手机短信验证")
                }else{
                    tempStr = XALanguageManager.getString(key: "谷歌验证器")
                }
                Defaults[.check_Type] = "2" //self.myuserModel.check_type
                if data1 == nil{
                    self.form.setValues(["昵称": self.myuserModel.nick_name,"验证方式":tempStr])
                }else{
                    self.form.setValues(["昵称": self.myuserModel.nick_name,"头像":UIImage(data:data1!),"验证方式":tempStr])
                }
                
 
                super.tableView.reloadData()
            }else{
                self.navigationController?.view.makeToast(XALanguageManager.getString(key: "失败"))
            }
            
        }) { (error) in
            //kLog(error.localizedDescription)
            self.navigationController?.view.makeToast(error.localizedDescription)
        }
    }
    
    func upLoadCheck_type(check_type: String) {
        MyNetwork.request(target: .updateUserinfo(user_id: Defaults[.userPhone]!, nick_name: "", headImg: "", check_type: check_type), success: { (result) in
            kLog(result)
            let needModel = BaseModel()
            needModel.yy_modelSet(with: result as! [AnyHashable : Any])
            if needModel.code == 1111{
                //                self.navigationController?.view.makeToast(needModel.message)
                
            }else{
                //                self.navigationController?.view.makeToast(needModel.message)
            }
            
        }) { (error) in
            //kLog(error.localizedDescription)
            self.navigationController?.view.makeToast(error.localizedDescription)
        }
    }
    
    
    func upLoadImage(imageStr: String) {
        MyNetwork.request(target: .updateUserinfo(user_id: Defaults[.userPhone]!, nick_name: "", headImg: imageStr, check_type: ""), success: { (result) in
            kLog(result)
            let needModel = BaseModel()
            needModel.yy_modelSet(with: result as! [AnyHashable : Any])
            if needModel.code == 1111{
//                self.navigationController?.view.makeToast(needModel.message)
                
            }else{
//                self.navigationController?.view.makeToast(needModel.message)
            }
            
        }) { (error) in
            //kLog(error.localizedDescription)
            self.navigationController?.view.makeToast(error.localizedDescription)
        }
    }
    //MARK - ui
    func makeBaseUI(){
        super.tableView.frame = CGRect(x: 15, y: 64, width: kScreenWidth - 30, height: kScreenHeight - 64)
        if #available(iOS 11.0.0, *) {
            super.tableView.frame = CGRect(x: 0, y: 0, width: kScreenW, height: kScreenHeight - 0)
        }
        super.tableView.frame = CGRect(x: 15, y: 64, width: kScreenWidth - 30, height: kScreenHeight - 64)
        if #available(iOS 11.0.0, *) {
            super.tableView.frame = CGRect(x: 0, y: 0, width: kScreenW, height: kScreenHeight - 0)
        }
        
        LabelRow.defaultCellUpdate = { cell, row in
            cell.textLabel?.textColor = .white
            cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 15)
            cell.textLabel?.textAlignment = .right
        }
        ImageRow.defaultCellUpdate = { cell, row in
            cell.textLabel?.textColor = .white
            cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 15)
            cell.textLabel?.textAlignment = .right
        }
        PushRow<String>.defaultCellUpdate = { cell, row in
            cell.textLabel?.textColor = .white
            cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 15)
            cell.textLabel?.textAlignment = .right
        }
        
        
        form +++ Section("")
            //为区域添加一个标签行
            <<< ImageRow(){
                $0.title = XALanguageManager.getString(key: "头像")
                $0.baseCell.backgroundColor = UIColor.clear
                $0.tag = "头像"
                let url1 : URL?
                if self.myuserModel.avatar == nil{
                    url1 = URL( string:String(format: "http://renedescartes.io%@", ""))
                }else{
                    url1 = URL( string:String(format: "http://renedescartes.io%@", self.myuserModel.avatar!))
                }
                
                //44f5dd23306614e83a40354a719e143e.jpg
                let data1 = try? Data( contentsOf:url1!)
                if data1 == nil{
                    
                }else{
                    $0.value =  UIImage.init(data:data1!)
                }
                

                $0.cell.height = { 60 }
                }.onChange({ row in
                    let imageData = UIImageJPEGRepresentation(row.value!, 0.1)
                    let formatter = DateFormatter.init()
                    formatter.dateFormat = "yyyyMMddHHmmss"
                    let str = formatter.string(from: NSDate.init() as Date as Date)
                    let fileName = str + ".jpg"
                    
                    let postImageURL = "YourPath"
                    
                    NetworkRequest.sharedInstance.upLoadImageRequest(urlString: "http://renedescartes.io/mobile/user/uploadimg", params: ["":""], data: [imageData!], name: ["imgcode"], success: { (success) in
                        let needModel = BaseModel()
                        needModel.yy_modelSet(with: success as [AnyHashable : Any])
                        let dic = NSDictionary(dictionary: needModel.mydata!)
                        self.upLoadImage(imageStr: dic["img_address"] as! String)
                        
                        super.tableView.reloadData()
                        //                        data img_address
                        //                        self.upLoadImage(imageStr: success)
                        
                    }, failture: { (error) in
                        
                    })
                    
                    
                })
                <<< LabelRow("昵称"){
                    $0.title = XALanguageManager.getString(key: "昵称");
                $0.tag = "昵称"
                $0.baseCell.textLabel?.textColor = UIColor.white
                $0.baseCell.backgroundColor = UIColor.clear
                $0.value = self.myuserModel.nick_name
                }//选中标签行会在tittle后面加上" Summer "
                .onCellSelection{cell, row in
//                    let proVC =  profileDetailViewController();
//                    proVC.changeStr = self.myuserModel.nick_name! as NSString
//                    proVC.callBackBlock { (str) in
//                        print(str)
//                        self.form.setValues(["昵称": str as String])
//                        self.myuserModel.nick_name = str
//                        super.tableView.reloadData()
//                    }
//                    self.navigationController?.pushViewController(proVC, animated: true)

                    
                    
                    //                    row.reload()
//                    guard let postValueBlock = postValueBlock else { return }
            }
//        form +++ Section("")
//            <<< LabelRow("dataRow"){
//                $0.title = XALanguageManager.getString(key: "换绑手机")
//                $0.baseCell.textLabel?.textColor = UIColor.white
//                $0.baseCell.backgroundColor = UIColor.clear
//                $0.baseCell.accessoryType = .disclosureIndicator
//                }.onCellSelection({ (cell, row) in
//                    self.navigationController?.pushViewController(changePhoneViewController(), animated: true)
//                    row.reload()
//
//                })
        form +++ Section("")
            //为区域添加一个勾选行，默认为选中
            <<< LabelRow("1"){
                $0.title = XALanguageManager.getString(key: "登录密码")
                $0.baseCell.textLabel?.textColor = UIColor.white
                $0.baseCell.backgroundColor = UIColor.clear
                
                $0.baseCell.accessoryType = .disclosureIndicator
                $0.value = ""
                }.onCellSelection({ (cell, row) in
                    if Defaults[.check_Type] == "2"{
                        self.navigationController?.pushViewController(googleChangePassWordDetailViewController(), animated: true)
                        row.reload()
                    }else{
                        self.navigationController?.pushViewController(changePassWordViewController(), animated: true)
                        row.reload()
                    }
                    
                    
                })
            
            
            <<< LabelRow("111"){
                $0.title = XALanguageManager.getString(key: "支付密码")
                $0.baseCell.textLabel?.textColor = UIColor.white
                $0.baseCell.backgroundColor = UIColor.clear
                $0.baseCell.accessoryType = .disclosureIndicator
                $0.value = ""
                
                }.onCellSelection({ (cell, row) in
                    if Defaults[.check_Type] == "2"{
                        self.navigationController?.pushViewController(googleChangePayPassWorldViewController(), animated: true)
                        row.reload()
                    }else{
                        self.navigationController?.pushViewController(changePayPassWordViewController(), animated: true)
                        row.reload()
                    }
                })
        
//            <<< PushRow<String>(){
//                $0.tag = "验证方式"
//                $0.baseCell.backgroundColor = UIColor.clear
//                $0.baseCell.textLabel?.textColor = UIColor.white
//                $0.title = XALanguageManager.getString(key: "验证方式")
//                $0.options = [XALanguageManager.getString(key: "手机短信验证"), XALanguageManager.getString(key: "谷歌验证器")]
//                $0.baseCell.selectionStyle = .none
//                $0.baseCell.accessoryType = .disclosureIndicator
//
//                $0.selectorTitle = ""
//                }.cellSetup { cell, row in
//                    cell.selectionStyle = .none
//                    cell.textLabel?.textColor = UIColor.white
//                }
//                .onChange({ (row) in
//                    self.form.rowBy(tag:"验证方式")?.updateCell()
//                    row.baseCell.selectionStyle = .none
//
//                    if row.value == XALanguageManager.getString(key: "手机短信验证"){
//                        self.upLoadCheck_type(check_type:"1")
//                        //Defaults[.check_Type] = "1"
//                        Defaults[.check_Type] = "2"
//                    }else{
//                        self.upLoadCheck_type(check_type:"2")
//                        Defaults[.check_Type] = "2"
//                    }
//
//
//
//                })
        
//
//            <<< SegmentedRow<String>("sex"){
//                $0.options = ["男", "女"]
//                $0.title = "性別"
//                $0.value = "男"
//                }.onChange{ row in
//                    let userDefault = UserDefaults.standard
//                    userDefault.setValue(row.value, forKey: "Sex")
//                }.cellUpdate({ (cell, row) in
//                    cell.segmentedControl.setWidth(30, forSegmentAt: 1)
//                    cell.segmentedControl.setWidth(30, forSegmentAt: 0)
//                    cell.titleLabel?.snp.makeConstraints({ (make) in
//                        make.right.equalTo(cell).offset(-100)
//                        make.left.equalTo(cell).offset(15)
//                        make.top.bottom.equalTo(cell)
//                    })
//                })
        
        
    }
    
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
//    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        if indexPath.row == 0 && indexPath.section == 0{
//            return 60
//        }else{
//            return 40
//        }
//    }
//
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        let tempCell = super.tableView.cellForRow(at: indexPath as IndexPath)
        tempCell?.accessoryType = .disclosureIndicator
    }
    
    
    
  
    
    func layoutNav() -> Void {
        self.title = XALanguageManager.getString(key: "个人信息")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
